
package pl.genapp.stocksense;

import java.io.ByteArrayOutputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import pl.genapp.appsense.R;
import pl.genapp.stocksense.libraries.FacebookHelper;
import pl.genapp.stocksense.libraries.SentGraph;
import pl.genapp.stocksense.libraries.SentGraph.OnSentClickListener;
import pl.genapp.stocksense.libraries.SentGraphArrow;
import pl.genapp.stocksense.libraries.SentGraphCircles;
import pl.genapp.stocksense.libraries.SentGraphPie;
import pl.genapp.stocksense.libraries.TwitterHelper;
import pl.genapp.stocksense.others.PostExecuteReaction;
import pl.genapp.stocksense.others.StockSenseState;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class EntityScreenHomeTopic {
	
	private static final String SHARE_DIALOG_NAME = "shareDalog";
	
	private EntityScreenFragment parent;
	private View layout;
	private LinearLayout topicBoxes[];
	private LinearLayout sentGraphPlaceOne;
	private View changeGraph1;
	private View changeGraph2;
	private View changeGraph3;
	private Button share;
	private View emptyInfo;
	private OnSentClickListener onSentClickListener = new OnSentClickListener() {
		
		public void onSentClick(int sentNo) {
			
			parent.getPager().setCurrentItem(0, true);
			
		}
	};
	
	public EntityScreenHomeTopic(EntityScreenFragment parent) {
		this.parent = parent;
	}
	
	View setupView() {
		
		Activity activity = parent.getActivity();
		
		if (activity != null) {
			
			layout = activity.getLayoutInflater().inflate(R.layout.fragment_entity_screen_one, null);
			setupContainer(layout);
			
			/**
			 * wykresy
			 */
			sentGraphPlaceOne = (LinearLayout) layout.findViewById(R.id.sentGraphPlaceOne);
			
			SentGraphPie sentGraph = new SentGraphPie(parent.getActivity(), null);
			
			sentGraphPlaceOne.addView(sentGraph);
			
			sentGraph.setOnSentClickListener(onSentClickListener);
			
			parent.loadTopThreeNewsData(((StockSenseState) parent.getActivity().getApplication()).getSelectedMonths());
			

			
			return layout;
		} else
			return null;
		
	}
	
	View getCurrentGraphView() {
		
		LinearLayout container = (LinearLayout) layout.findViewById(R.id.sentGraphPlaceOne);
		
		if (container.getChildCount() == 1) {
			return container.getChildAt(0);
		} else
			return null;
	}
	
	Bitmap getCurrentGraphBitmap() {
		
		View currentGraph = getCurrentGraphView();
		Bitmap image;
		
		if (currentGraph != null) {
			
			currentGraph.setDrawingCacheEnabled(true);
			image = Bitmap.createBitmap(currentGraph.getDrawingCache());
			currentGraph.setDrawingCacheEnabled(false);
			
			return image;
			
		} else
			return null;
		
	}
	
	byte[] getCurrentGraphBytes() {
		
		Bitmap image = getCurrentGraphBitmap();
		
		if (image != null) {
			
			byte[] data = null;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			image.compress(Bitmap.CompressFormat.PNG, 100, baos);
			data = baos.toByteArray();
			
			return data;
		} else
			return null;
		
	}
	
	void setupContainer(View layout) {
		
		/**
		 * Share
		 */
		share = (Button) layout.findViewById(R.id.shareHome);
		share.setOnClickListener(onShareClickListener);
		
		
		/**
		 * Empty info
		 */
		emptyInfo = layout.findViewById(R.id.emptyInfoImageHome);
		
		/**
		 * TopicBoxes
		 */
		
		topicBoxes = new LinearLayout[] { (LinearLayout) layout.findViewById(R.id.topic_box_1), (LinearLayout) layout.findViewById(R.id.topic_box_2),
				(LinearLayout) layout.findViewById(R.id.topic_box_3), (LinearLayout) layout.findViewById(R.id.topic_box_4), (LinearLayout) layout.findViewById(R.id.topic_box_5),
				(LinearLayout) layout.findViewById(R.id.topic_box_6) };
		
		// Listener
		OnClickListener listener = new OnClickListener() {
			public void onClick(View v) {
				
				int id = Integer.parseInt((String) v.getTag());
				
				// create fragment
				NewsScreenFragment newsFragment = NewsScreenFragment.newInstance(id);
				
				// fragment manager
				FragmentManager fragmentManager = parent.getFragmentManager();
				FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
				fragmentTransaction.replace(R.id.fragmentsSide, newsFragment).addToBackStack(parent.getEntityName() + (String) v.getTag());
				fragmentTransaction.commit();
			}
		};
		
		for (LinearLayout ll : topicBoxes) {
			ll.setOnClickListener(listener);
		}
		
		/**
		 * Change graph buttons
		 */
		OnClickListener onChangeGraph = new OnClickListener() {
			
			public void onClick(View v) {
				
				int buttonNr = Integer.parseInt(v.getTag().toString());
				SentGraph graphToAdd = null;
				
				switch (buttonNr) {
				
					case 1:
						graphToAdd = new SentGraphPie(parent.getActivity(), null);
						break;
					
					case 2:
						graphToAdd = new SentGraphCircles(parent.getActivity(), null);
						break;
					
					case 3:
						graphToAdd =  new SentGraphArrow(parent.getActivity(), null);
						break;
				
				}
				
				graphToAdd.setOnSentClickListener(onSentClickListener);
				
				sentGraphPlaceOne.removeAllViews();
				sentGraphPlaceOne.addView(graphToAdd);
				
			}
		};
		
		changeGraph1 = layout.findViewById(R.id.changeGraph1);
		changeGraph2 = layout.findViewById(R.id.changeGraph2);
		changeGraph3 = layout.findViewById(R.id.changeGraph3);
		
		changeGraph1.setOnClickListener(onChangeGraph);
		changeGraph2.setOnClickListener(onChangeGraph);
		changeGraph3.setOnClickListener(onChangeGraph);
		
	}
	
	void hideEmptyInfo() {
		
		emptyInfo.setVisibility(View.GONE);
		
	}
	
	PostExecuteReaction<JSONObject> topThreeNewsDataReaction = new PostExecuteReaction<JSONObject>() {
		
		public void onSuccess(Context context, JSONObject object) {
			 
			Log.d("stocksense", "TOP3 success!");
			
			// getData
			try {
				JSONArray dataArray = object.getJSONArray("data");
				
				for (int i = 0; i < dataArray.length(); i++) {
					
					JSONArray newsData = dataArray.getJSONArray(i);
					
					Log.d("stocksense", newsData.getString(0));
					
					((TextView) topicBoxes[i].findViewById(R.id.topThreeNewsOne)).setText(newsData.getString(0));
					((TextView) topicBoxes[i].findViewById(R.id.topThreeNewsTwo)).setText(newsData.getString(1));
					((TextView) topicBoxes[i].findViewById(R.id.topThreeNewsThree)).setText(newsData.getString(2));
					
				}
				
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			hideEmptyInfo();
			
		};
		
	};

	private OnClickListener onShareClickListener = new OnClickListener() {
		
		public void onClick(View v) {
			
			ShareDialogFragment dialogFragment = new ShareDialogFragment();
			dialogFragment.show(parent.getFragmentManager(), SHARE_DIALOG_NAME);
			
		}
	};
	
	/**
	 * ShareDialogFragment
	 */
	private class ShareDialogFragment extends DialogFragment {
		
		private View layout;
		private ImageView graph;
		private TextView text;
		private EditText description;
		private Button cancel;
		private Button shareTwitter;
		private Button shareFacebook;
		
		private String postAddtion = "See more on http://www.stocksense.com";
		private String postSeparator = "";
		private String postDescription = "";
		
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			
			layout = getActivity().getLayoutInflater().inflate(R.layout.dialog_share_home, null);
			
			graph = (ImageView) layout.findViewById(R.id.sharePreviewGraph);
			graph.setImageBitmap(getCurrentGraphBitmap());
			
			text = (TextView) layout.findViewById(R.id.sharePreviewText);
			text.setText(postDescription + postAddtion);
			
			cancel = (Button) layout.findViewById(R.id.sharePreviewCancel);
			cancel.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					
					dismiss();
					
				}
			});
			
			description = (EditText) layout.findViewById(R.id.sharePreviewDescription);
			description.addTextChangedListener(new TextWatcher() {
				
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					postDescription = s.toString();
					
					if (!postDescription.equals("")) {
						postSeparator = ". ";
					} else
						postSeparator = "";
					
					text.setText(postDescription + postSeparator + postAddtion);
				}
				
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {
					
				}
				
				public void afterTextChanged(Editable s) {
					
				}
			});
			
			shareFacebook = (Button) layout.findViewById(R.id.sharePreviewFacebook);
			shareFacebook.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					
					FacebookHelper facebookHelper = ((StackSense) parent.getActivity()).getFacebookHelper();
					
					if (facebookHelper.isLogged()) {
						facebookHelper.shareOnFacebook(getCurrentGraphBytes(), postDescription + postSeparator + postAddtion);
						Log.d("stocksense", "share!");
						dismiss();
					} else {
												
						startActivity(new Intent(parent.getActivity(), LoginActivity.class));
						
					}
					
				}
			});
			
			shareTwitter = (Button) layout.findViewById(R.id.sharePreviewTwitter);
			shareTwitter.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					
					TwitterHelper twitterHelper = ((StackSense) parent.getActivity()).getTwitterHelper();
					
					if (twitterHelper.isLoggedToTwitter()) {
						twitterHelper.postStatusWithImage(getCurrentGraphBytes(), postDescription + postSeparator + postAddtion);
						dismiss();
					} else {
						startActivity(new Intent(parent.getActivity(), LoginActivity.class));
					}
					
				}
			});
			
			AlertDialog.Builder builder = new AlertDialog.Builder(parent.getActivity());
			builder.setTitle("Share options");
			builder.setView(layout);
			
			return builder.create();
			
		}
	}
	
}
